package cn.antho.system.service.impl;

import cn.antho.system.domain.Menu;
import cn.antho.system.service.IMenuService;
import cn.antho.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author antho
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Override
    public List<Menu> tree() {
        List<Menu> menus= super.findAll();
        Map<Long, Menu> parentMap = menus.stream().collect(Collectors.toMap(Menu::getId, e -> e));
        ArrayList<Menu> result = new ArrayList<>();
        menus.forEach(e->{
            if (null == e.getParentId()) {
                result.add(e);
            } else {
                Menu parent = parentMap.get(e.getParentId());
                if (null == parent) {
                    return ;
                }
                List<Menu> children = parent.getChildren();
                children.add(e);
            }
        });
        return result;
    }
}
